package com.cloudsea.yunhaistores.controller;


import com.cloudsea.yunhaistores.dto.TableAddDTO;
import com.cloudsea.yunhaistores.entity.Tables;
import com.cloudsea.yunhaistores.service.TableService;
import com.cloudsea.yunhaiutils.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Tag(name = "商家-桌台管理", description = "用于商家在后台管理自己的桌台，如增删改查、生成二维码等")
@RestController
@RequestMapping("/tables")
public class TableController {

    @Autowired
    private TableService tableService;

    @Operation(summary = "添加新桌台", description = "为指定的门店添加一个新的桌台")
    @PostMapping("/add")
    public ApiResponse<Tables> addTable(@Valid @RequestBody TableAddDTO dto) {
        Tables newTable = tableService.addTable(dto);
        return ApiResponse.success("桌台添加成功", newTable);
    }

    @Operation(summary = "查询门店下的所有桌台", description = "根据门店ID，获取该门店的所有桌台列表")
    @GetMapping("/list")
    public ApiResponse<List<Tables>> listTablesByStoreId(@Parameter(description = "门店ID", required = true) @RequestParam Long storeId) {
        List<Tables> tables = tableService.listTablesByStoreId(storeId);
        return ApiResponse.success(tables);
    }

    @Operation(summary = "生成桌台的点餐二维码", description = "为指定的桌台ID生成一个专属的点餐二维码图片")
    @GetMapping("/{tableId}/qrcode")
    public void getTableQrCode(@Parameter(description = "桌台ID", required = true) @PathVariable Long tableId, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        try (OutputStream outputStream = response.getOutputStream()) {
            tableService.generateQrCode(tableId, outputStream);
        }
    }

    @Operation(summary = "清台/结束会话", description = "商家在确认顾客离座后调用此接口，将桌台恢复为空闲状态，并结束当前的点餐会话。")
    @PostMapping("/{tableId}/clear")
    public ApiResponse<Void> clearTable(
            @Parameter(description = "要清理的桌台ID", required = true)
            @PathVariable Long tableId
    ) {
        tableService.clearTable(tableId);
        return ApiResponse.success("桌台清理成功", null);
    }
}
